import axios from 'axios';
import { ElMessage } from 'element-plus';

const http = axios.create({
    // baseURL: 'http://123.56.122.168:8080/api/v1',
    baseURL: 'http://localhost:8080/api/v1',
    // timeout: 3000,
});

// request 拦截器
http.interceptors.request.use(
    config => {
        const token = localStorage.getItem('access-token');
        if (token) {
            config.headers['access-token'] = token;
        }
        return config;
    },
    error => {
        return Promise.reject(error);
    }
);

// response 拦截器
http.interceptors.response.use(
    response => {
        // 返回完整的响应对象，而不是仅返回 data
        if (response.status === 200) {
            return response.data;
        }else if (response.status === 201) {
            return response;
        }
        
    },  
    error => {
        if (error.response) {
            switch (error.response.status) {
                case 400:
                    ElMessage.error('请求错误');
                    break;
                case 401:
                    ElMessage.error('未授权，请重新登录');
                    localStorage.removeItem('access-token');             
                    localStorage.setItem('link', window.location.hash.substring(1));
                    setTimeout(() => {
                        window.location.href = '/';
                    }, 500);
                    break;
                case 403:
                    ElMessage.error('拒绝访问');
                    break;
                case 404:
                    ElMessage.error('请求错误,未找到该资源');
                    break;
                case 405:
                    ElMessage.error('请求方法未允许');
                    break;
                case 408:
                    ElMessage.error('请求超时');
                    break;
                case 500:
                    ElMessage.error('服务器端出错');
                    break;
                case 501:
                    ElMessage.error('网络未实现');
                    break;
                case 502:
                    ElMessage.error('网络错误');
                    break;
                case 503:
                    ElMessage.error('服务不可用');
                    break;
                case 504:
                    ElMessage.error('网络超时');
                    break;
                case 505:
                    ElMessage.error('http版本不支持该请求');
                    break;
                default:
                    ElMessage.error(`未知错误${error.response.status}`);
            }
        } else {
            ElMessage.error("连接到服务器失败");
        }
        return Promise.reject(error);
    }
);

export default http;